import babelpolyfill from 'babel-polyfill'
import Vue from 'vue'
import App from './App'
import ElementUI from 'element-ui'
import 'element-ui/lib/theme-default/index.css'
//import './assets/theme/theme-green/index.css'
import NProgress from 'nprogress'; // Progress 进度条
import 'nprogress/nprogress.css';// Progress 进度条 样式
// import VueRouter from 'vue-router'
import store from './vuex/store'
import Vuex from 'vuex'
//import NProgress from 'nprogress'
//import 'nprogress/nprogress.css'
import router from './routes'
// import Mock from './mock'
// Mock.bootstrap();
import 'font-awesome/css/font-awesome.min.css'
// import IconSvg from 'components/Icon-svg';// svg 组件

Vue.use(ElementUI)
// Vue.use(VueRouter)
Vue.use(Vuex)

//NProgress.configure({ showSpinner: false });

// register global progress.
const whiteList = ['/login', '/authredirect'];// 不重定向白名单
router.beforeEach((to, from, next) => {
  //NProgress.start();
  if (to.path == '/login') {
    sessionStorage.removeItem('user');
  }
  let user = JSON.parse(sessionStorage.getItem('user'));
  if (!user && to.path != '/login') {
    next({ path: '/login' })
  } else {
    if(store.getters.menus === undefined && user != null){        // 判断当前用户是否已拉取完user_info信息
      store.dispatch('GetInfo', user).then(data => {    // 拉取user_info
        const info = data.data;
        const menus = {};
        for(let i = 0; i < info.menus.length; i++){
         menus[info.menus[i].code] = true;
        }
        store.dispatch('GenerateRoutes', menus).then(() => { // 生成可访问的路由表
          router.addRoutes(store.getters.addRouters) // 动态添加可访问路由表
          // next({ ...to }); // hack方法 确保addRoutes已完成
          next(to.path); // hack方法 确保addRoutes已完成
        })
      }).catch(() => {
        store.dispatch('FedLogOut').then(() => {
          next({ path: '/login' });
        })
      })
    }else{
      next();
    }
  }
})

router.afterEach(() => {
  NProgress.done(); // 结束Progress
});

Vue.config.productionTip = false;

// 生产环境错误日志
if (process.env.NODE_ENV === 'production') {
  Vue.config.errorHandler = function(err, vm) {
    console.log(err, window.location.href);
    errLog.pushLog({
      err,
      url: window.location.href,
      vm
    })
  };
}

new Vue({
  el: '#app',
  router,
  store,
  template: '<App/>',
  components: { App }
})
